/**
 * Created by shenhai on 15/9/22.
 */

var questionService = require('../../../services/mis/question/questionService');
var messageUtil = require('../../../common/utils/messageUtil');
var toolUtil = require('../../../common/utils/toolUtil');
var redisKey = require('../../../config/redisKey');
var nodeExcel = require('excel-export');

exports.questionList = function(req, res) {

    questionService.questionListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
        }else {
            var data = {
                count:results[1]["count"],
                totalPage: results[1]["totalPage"],
                list: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

exports.updateQuestion = function(req, res) {

    questionService.updateQuestionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when updateQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when updateQuestion...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.setTopQuestion = function(req, res) {

    questionService.setTopQuestionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when setTopQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when setTopQuestion...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.deleteQuestion = function(req, res) {

    questionService.deleteQuestionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when deleteQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when deleteQuestion...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.shieldQuestion = function(req, res) {

    questionService.shieldQuestionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when shieldQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when shieldQuestion...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.acrossCityQuestion = function(req, res) {

    questionService.acrossCityQuestionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when acrossCityQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when acrossCityQuestion...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

//exports.replyList = function(req, res) {
//
//    questionService.replyListService(req, function(err, results) {
//
//        if (err) {
//            logger.error('Exception happen when replyList...' + err.message);
//            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when replyList...'));
//        }else {
//            res.json(messageUtil.composeSucceededMessage(req, null, {}));
//        }
//
//    });
//};
exports.exportQuestion = function (req, res) {

    var input = req.cparams;
    logger.debug(input);
    //var page = req.params.page;
    //var size = req.params.size;

    questionService.questionService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when exportQuestion...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when exportQuestion...'));
        } else {

            if(!results[1]) {
                logger.error('Exception happen when exportQuestion...导出数据为0' + err.message);
                res.json(messageUtil.composeSucceededMessage(req, null, {}));
            }else {
                var conf = {};


                conf.cols = [{
                    caption: '所属小区',
                    type: 'String'
                },{
                    caption: '浏览次数',
                    type: 'number'
                }, {
                    caption: '点赞次数',
                    type: 'number'
                }, {
                    caption: '描述',
                    type: 'String'
                },  {
                    caption: '类型',
                    type: 'String'
                }, {
                    caption: '回复/数量',
                    type: 'number'
                }, {
                    caption: '创建者ID',
                    type: 'String'
                }, {
                    caption: '创建者昵称',
                    type: 'String'
                }, {
                    caption: '创建者手机号',
                    type: 'String'
                },  {
                    caption: '发布时间',
                    type: 'String'
                }, {
                    caption: '最后修改时间',
                    type: 'String'
                }];

                var QuestionCategory = {
                    question: '邻里问问',
                    share: '随便说说',
                    essence: '66精选'
                };


                logger.debug(results);
                var data = results[1];
                var tempRows = new Array();
                logger.debug(data.length);
                for (var i = 0; i < data.length; i++) {
                    var temp = new Array();

                    if(data[i].community)temp.push(data[i].community.communityName);
                    if(data[i].browserCount){
                        temp.push(data[i].browserCount);
                    }else{
                        temp.push("0");
                    };
                    if(data[i].praiseCount){
                        temp.push(data[i].praiseCount);
                    }else{
                        temp.push("0");
                    };

                    temp.push(data[i].desc);
                    if(data[i].category){
                        temp.push( QuestionCategory[data[i].category]);
                    }else{
                        temp.push('');
                    }
                    if(data[i].replies) {
                        temp.push(data[i].replies.length);
                    }else{
                        temp.push("0");
                    }
                    logger.debug(i);
                    if(data[i].createdBy) {temp.push(data[i].createdBy._id.toString())}else{temp.push("");}
                    if(data[i].createdBy) {
                        temp.push(data[i].createdBy.nickName);
                        temp.push(data[i].createdBy.mobilePhone);
                    }else{
                        temp.push("");
                        temp.push("");
                    };

                    if (data[i].dateCreated != null) {
                        var dateCreated = new Date(data[i].dateCreated);
                        temp.push(dateCreated.getFullYear() + "-" + (dateCreated.getMonth() + 1) + "-" + dateCreated.getDate() + " " + dateCreated.getHours() + ":" + dateCreated.getMinutes());
                    } else {
                        temp.push("");
                    };

                    if (data[i].dateLastModified != null) {
                        var dateLastModified = new Date(data[i].dateLastModified);
                        temp.push(dateLastModified.getFullYear() + "-" + (dateLastModified.getMonth() + 1) + "-" + dateLastModified.getDate() + " " + dateLastModified.getHours() + ":" + dateLastModified.getMinutes());
                    } else {
                        temp.push("");
                    };

                    tempRows.push(temp);

                    //logger.debug(tempRows);
                };


                conf.rows = tempRows;

                var ret = nodeExcel.execute(conf);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                res.setHeader("Content-Disposition", "attachment; filename=" + "questionList.xlsx");
                res.end(ret, 'binary');
            }
        };

    });


};


// 回复@
exports.replyAtList = function(req, res) {

    questionService.replyAtListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when replyAtList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when replyAtList...'));
        }else {
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

/*  宝宝树66小区二次改造    add   gct  20170821   start   */

exports.personalLetterAtList = function(req, res) {

    questionService.personalLetterAtListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when replyAtList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when replyAtList...'));
        }else {
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};
/*  宝宝树66小区二次改造    add   gct  20170821   end   */
// 回复@ 处理
exports.replyAtUpdate = function(req, res) {

    questionService.replyAtUpdateService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when replyAtUpdate...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when replyAtUpdate...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


exports.questionReportList = function(req, res) {
    /*  宝宝树66小区二次改造    add   chenf  20170821   start   追加举报区分闲置和帖子*/
    // 帖子举报
    if (req.body.statusFlg == 1){
        questionService.questionReportListService(req, function(err, results) {

            if (err) {
                logger.error('Exception happen when questionList...' + err.message);
                /*  宝宝树66小区二次改造    mod   gct  20170901   start   */
             /*   res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));  旧*/
                if(err.status==999)
                {
                    res.json(messageUtil.composeSucceededMessage(req, null, err));
                }
                else {
                    res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
                }
                /*  宝宝树66小区二次改造    mod   gct  20170901   end   */
            }else {
                //logger.debug(results);
                var data = {
                    count:results[0]["count"],
                    totalPage: results[0]["totalPage"],
                    list: results[1]
                };
                res.json(messageUtil.composeSucceededMessage(req, null, data));
            }

        });
        // 闲置举报
    }else if (req.body.statusFlg == 2){
        questionService.goodsReportListService(req, function(err, results) {

            if (err) {
                logger.error('Exception happen when questionList...' + err.message);

                /*  宝宝树66小区二次改造    mod   gct  20170901   start   */
                /*  res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...')); 旧*/
                if(err.status==999)
                {
                    res.json(messageUtil.composeSucceededMessage(req, null, err));
                }
                else {
                    res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
                }
                /*  宝宝树66小区二次改造    mod   gct  20170901   end   */
            }else {
                //logger.debug(results);
                var data = {
                    count:results[0]["count"],
                    totalPage: results[0]["totalPage"],
                    list: results[1]
                };
                res.json(messageUtil.composeSucceededMessage(req, null, data));
            }

        });
    }
    /*  宝宝树66小区二次改造    mod   chenf  20170821   end   追加举报区分闲置和帖子*/
    /*questionService.questionReportListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
        }else {
            //logger.debug(results);
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });*/
};


exports.deleteQuestionReport = function(req, res) {

    questionService.deleteQuestionReportService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when deleteQuestionReport...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when deleteQuestionReport...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};

exports.rejectQuestionReport = function(req, res) {

    questionService.rejectQuestionReportService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when rejectQuestionReport...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when rejectQuestionReport...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


exports.ignoreQuestionReport = function(req, res) {

    questionService.ignoreQuestionReportService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when ignoreQuestionReport...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when ignoreQuestionReport...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }

    });
};


exports.questionPushList = function(req, res) {

    questionService.questionPushListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionPushList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionPushList...'));
        }else {
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

exports.questionPush = function(req, res) {

    questionService.questionPushService(req, function(err, results) {
        if (err) {
            logger.error('Exception happen when questionPush...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionPush...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }
    });
};

exports.questionReplyList = function(req, res) {

    questionService.questionReplyListService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionPushList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionPushList...'));
        }else {
            var data = {
                count:results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

exports.deleteReply = function(req, res) {

    questionService.deleteReplyService(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when deleteReply...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when deleteReply...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));

            redisClient.del('question:reply:list:' + req.body.contentId);
            logger.debug(results[2]);
            if (req.body.replyBy != results[2].createdBy + '')
                toolUtil.hessianInvokeAddScore( req.body.replyBy, 32, null, function (value) {
                });
            logger.debug(req.body);
            //统计用户数据
            redisClient.HINCRBY(redisKey.getUserDataStatisticKey(req.body.replyBy), 'questionReply', -1);
        }

    });
};
